package com.wlstock.funi.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.constant.SharePrefConstants;
import com.wlstock.funi.constant.URLConstant;
import com.wlstock.funi.dao.MyAccountStockDao;
import com.wlstock.funi.dao.OperateDao;
import com.wlstock.funi.dao.SelfFundDao;
import com.wlstock.funi.model.MyAccountStocks;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.request.CustomStringRequest;
import com.wlstock.funi.request.EventBusConstants;
import com.wlstock.funi.request.NetWorkListener;
import com.wlstock.funi.request.RequestEvent;
import com.wlstock.funi.runnable.OrderBuy;
import com.wlstock.funi.runnable.OrderListener;
import com.wlstock.funi.runnable.OrderSale;
import com.wlstock.funi.utils.CaculateUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.SharePreferenceUtils;
import com.wlstock.funi.utils.TimeUtils;
import com.wlstock.funi.utils.TradeSetUtils;

import de.greenrobot.event.EventBus;

import static com.wlstock.funi.app.FundApplication.isDebugMode;

public class TimerService extends Service implements NetWorkListener, TaskLitener<String, Void>,OrderListener {
	private static final String TAG = "TimerService";
	private final IBinder myBinder = new TimerServiceBinder();
	private final String OPERAT_LIST = "1";//操作列表
//    private final String TRADE_TRACK = "2";//交易跟踪
    private boolean isInRange = true;
    
	@Override
	public IBinder onBind(Intent intent) {
		Log.e(TAG, "onBind()");
		Toast.makeText(this, "onBind()", Toast.LENGTH_SHORT).show();
		return myBinder;
	}

	// 调用startService方法或者bindService方法时创建Service时（当前Service未创建）调用该方法
	@Override
	public void onCreate() {
		Log.e(TAG, "onCreate()");
		EventBus.getDefault().register(this);
		Toast.makeText(this, "onCreate()", Toast.LENGTH_SHORT).show();
	}


	// 调用startService方法启动Service时调用该方法
	@Override
	public void onStart(Intent intent, int startId) {
		
		Log.e(TAG, "onStart()");
		boolean isDebugMode = SharePreferenceUtils.getBoolSP(this,SharePrefConstants.IS_DEBUG_MODE,false);
		if (!isDebugMode){
			isInRange = TimeUtils.isHourInRange("09:15","15:10",new Date());
		}else {
			isInRange = true;
		}
		
		if (isInRange) {
			if (FundApplication.isLogSuccess) {
				FundApplication.requestTimes++;
				//20秒启动一次 3次一分钟， 每5分钟进行一下页面访问，用来维持session对话
				if (FundApplication.requestTimes % 15 ==0) {
//					RefreshLogSession.getInstance().refresh(null);
					FundApplication.requestTimes = 0;
					
//					CurPosition curPosition = new CurPosition();
//					curPosition.requset();
				}
			}
			if (SharePreferenceUtils.getBoolSP(this, SharePrefConstants.IS_WANGLONG_REQ, true)){
				HashMap<String, String> parms = new HashMap<String, String>();
				parms.put("act", OPERAT_LIST);
				CustomStringRequest curRequest = new CustomStringRequest();
				curRequest.networkResponseListener = this;
				curRequest.requestGet(URLConstant.WLHOST, URLConstant.WL_TRADE_TRACK, null, parms);
			}
		}
	}

	// Service创建并启动后在调用stopService方法或unbindService方法时调用该方法
	@Override
	public void onDestroy() {
		Log.e(TAG, "onDestroy()");
	}
	
	public void onEvent(RequestEvent event){
		if (event.getWhat() == EventBusConstants.EVENT_OPERATE) {
			Log.e(TAG, "regist event onBackground()");
		} else if (event.getWhat() == EventBusConstants.EVENT_REFRESH_LOGIN_SESSION_SUCCESS) {
			Toast.makeText(this, event.getResponse(), 1000).show();
		} 
		
	}

	@Override
	public void orderSuccess(int tradeType, String stkcode, String stkName, float price, long qty) {

	}

	@Override
	public void orderFaile(int tradeType, String stkcode, String stkName, float price, long qty, String info) {

	}


	//提供给客户端访问
	public class TimerServiceBinder extends Binder {
		TimerService getService() {
			return TimerService.this;
		}
	}



	@Override
	public void onErrorResponse(VolleyError error, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onErrorResponse(VolleyError error, String eventCode) {
		// TODO Auto-generated method stub
		if (URLConstant.WL_TRADE_TRACK.equals(eventCode)) {
			
		}
	}

	@Override
	public void onResponse(String response, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onResponse(String response, String eventCode) {
		// TODO Auto-generated method stub
		if (URLConstant.WL_TRADE_TRACK.equals(eventCode)) {
			FundAsyTask<String, Void, Void> task = new FundAsyTask<String, Void, Void>();
			task.backListener = this;
			task.execute(response);
		}
	}

	@Override
	public Void doInBackground(String... params) {
		// TODO Auto-generated method stub
		try {
			JSONObject obj = new JSONObject(params[0]);
			String format = TimeUtils.patternDate(obj.getString("datas"));
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
			List<OperateModel> models = gson.fromJson(format, new TypeToken< List<OperateModel> >(){}.getType());
			String season = new SimpleDateFormat("yyyyMM").format(new Date());
			
			for (int i = 0; i < models.size(); i++) {
				OperateModel model = models.get(i);
				HashMap<String, Integer> rangeHash = CaculateUtils.getModelRangeFromList(model, models);
				
				model.setSeason(Long.valueOf(season));
				model.nums = rangeHash.get("num")!=null?rangeHash.get("num"):0;
				model.range = rangeHash.get("range")!=null?rangeHash.get("range"):0;
				
				if (model.getStockHoldDetailId()!=null) {
					if (OperateDao.getInstance(this).queryModelByStockHoldDetailId(model.getStockHoldDetailId())==null) {
						OperateDao.getInstance(this).addOperation(model);
						
						NotiUtils.showOperateModeNoti(this, model);
						
						long pty = CaculateUtils.getTradePty(this, model.getFundid(), model.getTradePrice(), model.nums);
						//登录成功，而且是买入,而且买入数量不为0
						if (FundApplication.isLogSuccess && model.getTradeType()==OperateModel.TradeType_BUY&& pty>0 &&TradeSetUtils.getIsTrackBuy(this, model.getFundid())) {
							float buyOffset = TradeSetUtils.getBuyOffset(this, model.getFundid());
							float price =CaculateUtils.getBuyPrice(model.getTradePrice(), buyOffset);
							OrderBuy orderBuy = new OrderBuy(model,model.getStockNo(), model.getStockName(),price, pty);
							orderBuy.buy(this);
							//买入操作的加入自选
//							SelfFundDao.getInstance(this).addWithOperateMode(model);
						} else if (FundApplication.isLogSuccess && model.getTradeType()==OperateModel.TradeType_SELL && TradeSetUtils.getIsTrackSaile(this, model.getFundid())) {
							MyAccountStocks queryStock = MyAccountStockDao.getInstance(this).queryStock(model.getStockNo());
							if(queryStock != null && queryStock.getStkQty() != 0){
								//以 Operatemodel的 Tradeprice作为交易的计算价格
								float saileOffset = TradeSetUtils.getSaleOffset(this, model.getFundid());
								float price = CaculateUtils.getSellPrice(model.getTradePrice(), saileOffset);
								OrderSale orderSale = new OrderSale(model, model.getStockNo(), model.getStockName(),price, queryStock.getStkQty());
								orderSale.saile(this);
							}else {
								NotiUtils.cancelNoti(TimerService.this, NotiIdGenerator.generate(model.getStockNo(), NotiIdGenerator.GenerFrom.SELFFUND));
								//卖出操作而且自己没有持仓,则从自选中删除
//								SelfFundDao.getInstance(this).deleteWithStkNo(model.getStockNo());
							}
						}
					}
				}
			}	
			
			SelfFundDao.getInstance(this).addWithOperateModeList(models);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}


	
}
